package com.lagou.demo.security;

import com.lagou.demo.service.SecurityService;
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouInterceptor;
import com.lagou.edu.mvcframework.pojo.Handler;
import com.lagou.edu.mvcframework.pojo.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author leonzhangxf
 */
@LagouInterceptor
public class SecurityInterceptor implements Interceptor {

    @LagouAutowired
    private SecurityService securityService;

    @Override
    public boolean intercept(Handler handler, Object[] args,
                             HttpServletRequest request, HttpServletResponse response) {
        // test interceptor di
        System.out.println(securityService.fakeSecurityProcess());

        Optional<Security> securityOpt = getSecurityInfo(handler);
        if (securityOpt.isEmpty()) {
            return true;
        }
        String username = request.getParameter("username");
        Security security = securityOpt.get();

        boolean hasAccessRight = Arrays.asList(security.value()).contains(username);
        if (hasAccessRight) {
            return true;
        }

        try {
            response.setStatus(200);
            response.setContentType("text/html; charset=utf-8");
            response.getWriter().write(String.format("%s no access", username));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private Optional<Security> getSecurityInfo(Handler handler) {
        if (!handler.getController().getClass().isAnnotationPresent(Security.class)
            && !handler.getMethod().isAnnotationPresent(Security.class)) {
            return Optional.empty();
        }

        Security annotationClass = handler.getController().getClass().getAnnotation(Security.class);
        Security annotationMethod = handler.getMethod().getAnnotation(Security.class);

        if (null != annotationMethod && null != annotationMethod.value() && annotationMethod.value().length > 0) {
            return Optional.of(annotationMethod);
        }
        if (null != annotationClass && null != annotationClass.value() && annotationClass.value().length > 0) {
            return Optional.of(annotationClass);
        }
        return Optional.empty();
    }
}
